package com.sxt.portal.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.sxt.commons.dto.ApiCreateOrderResponse;
import com.sxt.commons.typeEnum.ApiStatusEnum;
import com.sxt.commons.utils.RequestUtils;
import com.sxt.commons.utils.ResultUtils;
import com.sxt.portal.service.CreateOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class SignInterceptor implements HandlerInterceptor {
    protected final Logger logger = LoggerFactory.getLogger(SignInterceptor.class);
    //在执行handler之前来执行的
    //用于api接口验签
    @Autowired
    private CreateOrderService createOrderService;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        Boolean flag = false;
        Map<String, Object> params = RequestUtils.getRequestParams(request);
        Map<String, Object> result = null;
        Object fromSign = params.get("sign");
        if(params==null||fromSign==null){
            result = ResultUtils.createStatusResult(ApiStatusEnum.ARGUMENT_ERR.getCode().toString()
                    , "参数错误");
        }
        //获取签名（暂时这样，后面改成：在此进行签名，做一个认证，取出秘钥，过期再进行登录，去掉远程调用）
        String mySign = createOrderService.createSign(params,params.get("mchId").toString());
        if(mySign.equals(fromSign)){
            return true;
        }else {
            logger.info("签名错误:fromSign="+fromSign+",mySign="+mySign);
            result = ResultUtils.createStatusResult(ApiStatusEnum.SIGN_ERR.getCode().toString()
                    , "签名错误");
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(JSONObject.toJSONString(ApiCreateOrderResponse.error(result)));
        return flag;
    }





}

